package share.storage;

import java.io.IOException;

import org.eu.config.Config;
import org.eu.config.ConfigManager;
import org.eu.config.ConfigMissingException;

import share.storage.io.File;
import share.storage.io.FileLoadParameter;

/**
 * 目录树
 * 
 * @author wzz
 */
public class DirectoryTree {

	private RootFile root = new RootFile();
	private final String DEFAULT_LOADER = "default";
	private static DirectoryTree instance = new DirectoryTree();

	/**
	 * @return 目录树实例
	 */
	public static DirectoryTree getInstance() {
		return instance;
	}

	public File findByPath(String path) {
		File file = root;
		StringBuffer sb = new StringBuffer(path);
		String name = null;
		int index = 0;
		while (sb.length() > 0) {
			if (sb.charAt(0) == '/') {
				sb.deleteCharAt(0);
				continue;
			}
			index = sb.indexOf("/");
			if (index > 0) {
				name = sb.substring(0, index);
				sb.delete(0, index);
			} else {
				name = sb.toString();
				sb.setLength(0);
			}
			file = file.findChildByName(name);
			if (file == null)
				break;
		}
		return file;
	}

	private DirectoryTree() {
		Config cfg = ConfigManager.getGlobalConfig("share.dir");
		if (cfg == null) {
			System.err.println("DirectoryTree:No Config Found");
			return;
		}
		String name = null;
		String path = null;
		String loader = null;
		FileLoadParameter para = null;
		int i = 1;
		while (true) {
			try {
				name = cfg.getValue("dir" + i);
				path = cfg.getValue("dir" + i + ".path");
			} catch (ConfigMissingException e) {
				break;
			}
			loader = cfg.getValueNE("dir" + i + ".loader");
			if (loader == null)
				loader = DEFAULT_LOADER;
			para = new FileLoadParameter(path,name, loader);
			File file;
			try {
				file = LoaderFactory.newLoaderByName(loader).load(para);
			} catch (IOException e) {
				System.err.println("Error occurs while loading "+path+",message: "+e.getLocalizedMessage());
				continue;
			}
			if (file != null) {
				file.setFileName(name);
				root.addChild(file);
				file.setParent(root);
			}
			i++;
		}
		System.out.println("DirectoryTree init done");
	}

	/**
	 * @return the root
	 */
	public File getRoot() {
		return root;
	}

}
